<template>
  <div id="ArticleList">
    <ul>        
      <li 
        v-for="(item, index) in articleList" :key="index"        
        :style="{
          backgroundImage: `url(${baseURL}${item.cover})`
        }"
      >
        <div class="content">
          <p>{{ `${item.title}` }} </p>
          <p>{{`${formatDate(item.date)}・${articleClassify(item.classify)}`}}</p>
        </div>
        <router-link :to="`/article/${item._id}`">
          <div class="img-mask"></div>
        </router-link>
      </li>
    </ul>
    <div v-if="pageType !== 'search'">
      <div class="loading" v-show="isReq && articleList.length === 0">加载中...</div>
      <div v-show="isShowGroupBtn" class='group-btn'>
        <el-button v-show="isShowPrevBtn" :disabled="isReq" round @click="prevHandler">上一页</el-button>
        <el-button v-show="isShowNextBtn" :disabled="isReq" round @click="nextHandler">下一页</el-button>
      </div>
      <div class="clear"></div>
    </div>
    <h2 class='noarticle' v-if="pageType === 'search' && articleList.length === 0">{{articleList.length === 0 ? "没有找到内容": ""}}</h2>
  </div>
</template>

<script>
export default {
  name: 'ArticleList',
  props: {
    pageType: {
      type: String, 
      required: true
    },
  },
  data(){
    return{
      articleList: [],
      isShowGroupBtn: false,
      isShowPrevBtn: false,
      isShowNextBtn: false,
      isReq: false,
      pageCount: 5,
      curPage: 0,
      totalCount: 0
    }
  },
  mounted(){
    if(this.pageType !== 'search'){
      this.initShowList()
    }else{
      this.getArticleList()
    }
    this.monitorClientWidth()
  },
  watch: {
    '$route':'getPath'
  },
  methods:{
    // 监听可视区宽度
    monitorClientWidth(){      
      this.setWidthForWX()
      window.onresize = () => {
        this.setWidthForWX()
      }
    },
    // 设置微信浏览器内的宽度
    setWidthForWX(){
      if(document.body.clientWidth <= 600){
        let sUserAgent = navigator.userAgent.toLowerCase()
        let isWXBrowser = /micromessenger/.test(sUserAgent)
        if(isWXBrowser){
          let con = document.getElementById('ArticleList')
          con.style.maxWidth = '30rem'
        }
      }
    },
    getPath(){
      this.curPage = 0
      if(this.pageType === 'classify'){        
        this.classify = +this.$route.params.classify
        this.initShowList()
      }
      if(this.pageType === 'search'){
        this.getArticleList()
      }
    },
    async getArticleList(){
      let ids = this.$route.params.idArr
      let {data} = await this.$axios({
        method: 'post',
        url: '/article/searchIds',
        data: {ids}
      })
      if(data.code){
        return this.$message.error(data.msg)
      }
      // console.log(data.data);
      this.articleList = data.data
    },
    async initShowList(){
      this.isReq = true
      let sendData = {}
      if(this.pageType === 'home'){
        sendData = {
          curPage: this.curPage,
          pageSize: this.pageCount
        }
      }else if(this.pageType === 'classify'){
        this.classify = +this.$route.params.classify
        sendData = {
          curPage: this.curPage,
          pageSize: this.pageCount,
          classify: this.classify
        }        
      }
      let {data} = await this.$axios({
        method: 'post',
        url: '/article/list',
        data: sendData
      })
      this.totalCount = data.data.totalCount
      this.articleList = data.data.list
      this.isShowGroupBtn = this.totalCount > this.pageCount
      if(this.isShowGroupBtn){
        setTimeout(() => {
          this.$zh_tran(localStorage.getItem('lang'))
          this.$setFont("#app", "SourceHanSerifCN-Medium")
        }, 200)

        this.showNext()
        this.showPrev()
      }
      this.isReq = false
    },
    prevHandler(){
      if(this.curPage <= 0){
        this.curpage = 0
        return
      }
      this.curPage--
      this.initShowList()
    },

    nextHandler(){
      this.curPage++
      this.initShowList()
    },
    showPrev(){
      if(this.curPage !== 0){
         this.isShowPrevBtn = true
      }else{
        this.isShowPrevBtn = false
      }
    },
    showNext(){
      if(this.articleList.length < this.pageCount){
        this.isShowNextBtn = false
        this.isShowPrevBtn = true
      }else{
        if((this.curPage+1) * this.pageCount === this.totalCount){
          // 如果下一页的总数和文章总数相等，则为最后一页
          this.isShowPrevBtn = true
          this.isShowNextBtn = false
        }else{
          this.isShowNextBtn = true
          this.isShowPrevBtn = false
        }        
      }
    },
    articleClassify(classify){
      return classify === 1 ? "日常" : "技术"
    },
    //处理时间格式
    formatDate(val) {
      let date = new Date(val),
        YY = date.getFullYear(),
        MM = date.getMonth() + 1,
        DD = date.getDate(),
        hh = date.getHours(),
        mm = date.getMinutes(),
        ss = date.getSeconds()

      hh < 10 && (hh = '0' + hh)
      mm < 10 && (mm = '0' + mm)
      ss < 10 && (ss = '0' + ss)

      return `${YY} 年 ${MM} 月 ${DD} 日`
    }
  }
}
</script>

<style lang="less" scoped>
@liWidth: 46rem;
@liHeight: 15rem;

#ArticleList{
  width: @liWidth;
  margin: 3rem auto;
  margin-bottom: 3rem;
  // overflow: hidden;
  ul{
    display: flex;
    flex-direction: column;
    justify-content: space-between;      
    li{
      position: relative;
      width: inherit;
      height: @liHeight;
      background-color: #99a2aa;
      margin: 1rem 0;
      background-size: cover;
      background-position: center center;
      border-radius: 5px;
      cursor: pointer;
      -webkit-transition: .3s;
      -moz-transition: .3s;
      -ms-transition: .3s;
      -o-transition: .3s;
      transition: .3s;

      .img-mask{
        width: inherit;
        height: @liHeight;
        background-color: rgba(255, 255, 255, 0);
      }

      .content{
        user-select: none;
        pointer-events: none;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
        font-weight: 400;
        p:nth-child(1){            
          font-size: 1.8rem;
        }
        p:nth-child(2){
          font-size: 0.625rem;
          margin-top: 5px;
        }
      }
      
      &:hover{
        transform: translateY(-4px) scale(1.05);
        box-shadow: 0 1rem 2rem rgba(0, 0, 0, .2);
      }
    }
  }

  .noarticle{
    font-size: 2rem;
    margin: 3rem 0;
  }

  .group-btn{
    position: relative;
    float: right;
    margin-top: 3rem;
    /deep/ .el-button{
      width: 10rem;
      border: 1px solid #333;
      color: #333;
      -webkit-transition: .3s;
      -moz-transition: .3s;
      -ms-transition: .3s;
      -o-transition: .3s;
      transition: .3s;
    }

    .el-button:hover{
      background-color: #333;
      color: #fff;
    }
  }

  .loading{
    margin: 3rem auto 0;
    background-color: #333;
    color: #fff;
    width: 100px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  .clear{
    clear: both;
  }
}


/* 很小的设备（手机等，小于 600px） */
@media only screen and (max-width: 600px) { 
  #ArticleList {
    max-width: 32rem;
  }
}

/* 比较小的设备（竖屏的平板，屏幕较大的手机等, 大于 600px） */
@media only screen and (min-width: 600px) { 
  #ArticleList {
    min-width: 34rem;
  }
}

/* 中型大小设备（横屏的平板, 大于 768px） */
@media only screen and (min-width: 768px) { 
  #ArticleList {
    min-width: 38rem
  }
}

/* 大型设备（电脑, 大于 992px） */
@media only screen and (min-width: 992px) { 
  #ArticleList {
    min-width: 42rem;
  }
}

/* 超大型设备（大尺寸电脑屏幕, 大于 1200px） */
@media only screen and (min-width: 1200px) { 
  #ArticleList {
    min-width: 46rem;
  }
}
</style>